package com.example.security;

import cn.hutool.json.JSONUtil;
import com.example.domain.vo.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 在未认证或者认证错误的情况下访问需要认证的资源时的处理类
 */
@Component  //加入到IOC容器
public class LoginUnAuthenticationEntryPointHandler implements AuthenticationEntryPoint {
    /*
     * 当访问一个需要认证的资源时因为当前用户没有认证或者认证失败，直接访问资源会交给此函数进行处理
     * 因为架构是前后端分离的项目,所以给客户端的提示保持和控制器的返回值格式相同
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        Result result = Result.error("用户未认证或登录已过期，请重新登录后再访问");
        //将消息json化
        String json = JSONUtil.toJsonStr(result);
        //送到客户端
        response.getWriter().print(json);
    }
}